/**
* Module: 
* Description: 角色控制器
* Author: xsq
* Date: 2023/04/26 23:39:25
* LastEditAuthor: xsq
* LastEditTime: 2023/04/26 23:39:25
*/

const groupModel = require('../model/group');
const ruleModel = require('../model/rule');
const { connect } = require("../model/index");
const config = require("../config/index");

/**
 * 获取角色列表
 * @method: get
 * @param {*} ctx
 * @param {*} next
 */
const getGroupList = async (ctx, next) => {
  const query = ctx.request.query;
  const pageSize = Number(query.pageSize || 10);
  const pageNum = Number(query.pageNum || 1) - 1;
  const database = groupModel.TABLE_NAME;
  let [rows, fields] = await connect.query(
    `select * from ${database} where status = ? order by id desc limit ? offset ?`,
    [1, pageSize, pageNum * pageSize]
  );
  let [countRows] = await connect.query(
    `select count(id) as count from ${database} where status = ?`,
    [1]
  );

  const pageCount = Math.ceil(countRows[0].count / pageSize); // 总页数
  ctx.body = {
    data: {
      datas: rows,
      pageNum: pageNum + 1,
      pageSize: pageSize,
      pageCount: pageCount,
      total: countRows[0].count || 0
    },
    code: 200,
    msg: '查询成功',
  };
  await next();
};

/**
 * 添加角色
 * @method: post
 * @param {*} ctx 
 * @param {*} next 
 */
const addGroup = async (ctx, next) => {
  const query = ctx.request.body;
  const saveData = {
    title: query.title, // 角色名
    rules: query.rules, // 权限id
    pid: 0,
    remark: query.remark || '', // 备注
    status: 1,
  };
  let fields = [];
  let values = [];
  for(let key in saveData) {
    if (key != 'id') {
      fields.push(key);
      values.push(`'${saveData[key]}'`);
    }
  }

  const database = groupModel.TABLE_NAME;
  const connection = await connect.getConnection();

  try {
    // 开启事务
    await connection.beginTransaction();

    await connection.query(
      `
        INSERT INTO ${database}
        (${fields.join(',')})
        VALUES (${values.join(',')})
      `
    );
    await connection.commit();
  } catch(err) {
    await connection.rollback();
    ctx.throw(new Error(err));
  } finally {
    // connection.releaseConnection();
    connection.release();
  }

  ctx.body = {
    data: null,
    code: 200,
    msg: '操作成功',
  };
  await next();
}

/**
 * 修改角色权限
 * @method: post
 * @param {*} ctx
 * @param {*} next
 */
const saveGroupRule = async (ctx, next) => {
  const query = ctx.request.body;
  const saveData = {
    id: query.id,
    rules: query.rules, // 权限id
    title: query.title,
    remark: query.remark || ''
  };
  let sqlArr = [];
  for(let key in saveData) {
    if (key != 'id') {
      sqlArr.push(`${key}='${saveData[key]}'`);
    }
  }
  
  const database = groupModel.TABLE_NAME;
  const connection = await connect.getConnection();

  try {
    // 开启事务
    await connection.beginTransaction();

    await connection.query(
      `
        UPDATE ${database}
        SET ${sqlArr.join(',')}
        WHERE id = ? and status = 1
      `,
      [Number(query.id)]
    );
    await connection.commit();
  } catch(err) {
    await connection.rollback();
    ctx.throw(new Error(err));
  } finally {
    // connection.releaseConnection();
    connection.release();
  }
  
  ctx.body = {
    data: {},
    code: 200,
    msg: '操作成功',
  };
  await next();
};

/**
 * 获取角色所属权限
 * @method: get
 * @param {*} ctx
 * @param {*} next
 */
const getGroupRuleList = async (ctx, next) => {
  const query = ctx.request.query;
  const groupId = Number(query.id);
  const database = groupModel.TABLE_NAME;
  const ruleTable = ruleModel.TABLE_NAME;
  let [groupRows, fields] = await connect.query(
    `select * from ${database} where status = ? and id = ? order by id`,
    [1, groupId]
  );
  let ids = groupRows[0].rules ? groupRows[0].rules : '';
  ids = ids.split(',');
  let [rows] = await connect.query(
    `select * from ${ruleTable} where status = ? and id in (?) order by id`,
    [1, ids]
  );
  ctx.body = {
    data: {
      datas: rows
    },
    code: 200,
    msg: '查询成功',
  };
  await next();
};

/**
 * 删除角色
 * @method: get
 * @param {*} ctx 
 * @param {*} next 
 */
const deleteGroupById = async (ctx, next) => {
  const query = ctx.request.query;
  const id = query.id;

  const database = groupModel.TABLE_NAME;
  const connection = await connect.getConnection();

  try {
    // 开启事务
    await connection.beginTransaction();

    await connection.query(
      `
        DELETE FROM ${database}
        where id = ?
      `,
      [id]
    );
    await connection.commit();
  } catch(err) {
    await connection.rollback();
    ctx.throw(new Error(err));
  } finally {
    // connection.releaseConnection();
    connection.release();
  }

  ctx.body = {
    data: {},
    code: 200,
    msg: '操作成功',
  };
  await next();
};

module.exports = {
  getGroupList,
  addGroup,
  saveGroupRule,
  getGroupRuleList,
  deleteGroupById
};